package com.yunkeji.config.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.spring.SpringUtil;

import com.yunkeji.common.enums.app.AccountTypeEnums;
import com.yunkeji.common.exception.AppServiceException;
import com.yunkeji.common.helper.LoginHelper;
import com.yunkeji.config.annotation.ApiAuth;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * api权限拦截
 *
 * @author 老张
 */
@Aspect
@Component
public class ApiAuthAspect {

    private static final ThreadLocal<String> KEY_CACHE = new ThreadLocal<>();
    private static String EVN = SpringUtil.getActiveProfile();

    private List<String> excludedUrls;

    @Around("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        // 暂时取消了API接口的账号访问限制
//        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//        ApiAuth apiAuth = signature.getMethod().getDeclaredAnnotation(ApiAuth.class);
//        if (StpUtil.isLogin()) {
//            Integer accountType = LoginHelper.getLoginUser().getAccountType();
//            if (apiAuth == null && !accountType.equals(AccountTypeEnums.用户.getCode())) {
//                // 所有的接口默认只能用户访问,其他类型的角色想要访问需要使用@ApiAuth
//                throw AppServiceException.paramException("当前账号暂无权限访问");
//            }
//            if (apiAuth != null) {
//                AccountTypeEnums[] forbid = apiAuth.allow();
//                if (forbid.length > 0) {
//                    if (!Arrays.stream(forbid)
//                            .anyMatch(item -> item.getCode().equals(accountType))) {
//                        throw AppServiceException.paramException("当前账号暂无权限访问");
//                    }
//                }
//            }
//        }
        // 在方法执行前执行的逻辑
        Object result = joinPoint.proceed();
        // 在方法执行后执行的逻辑
        return result;
    }
}
